package com.baseLearn.api.aspects;

import com.baseLearn.annotation.UserAccess;
import com.baseLearn.api.util.UserManage;
import com.baseLearn.api.web.ResponseUtil;
import com.baseLearn.pojo.Enums.EmUserAccess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author huangz
 * @Title: TokenAccessAspect
 * @ProjectName zjmsa_oa
 * @Description: token验证
 * @date 2018/10/23 13:03
 */
@Component
@Aspect
@Slf4j
public class TokenAccessAspect {

    public static final String TOKEN_FAIL = "token无效";
    public static final String TOKEN = "token";
    @Autowired
    private UserManage userManage;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Pointcut(value = "execution(* com.baseLearn.controller..*(..))")
    public void access() {

    }


    @Around("access()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest req = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
        String Ip = getIpAddr(req);//获取被拦截的IP
        log.info("请求的Ip：{}", Ip);
        String uri = req.getRequestURI();//获取uri
        uri = uri.replaceAll("/+", "/");//访问路径中有可能有多个/
        log.info("请求的Uri：{}", uri);

        Signature signature = pjp.getSignature();
        if (Arrays.asList(ExcludePathPatternsConstants.RELEASE_METHOD).contains(uri)) {//无需验证放行的方法f
            return pjp.proceed();
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();//获取接口方法
        Method realMethod = pjp.getTarget().getClass().getDeclaredMethod(signature.getName(), targetMethod.getParameterTypes());//获取具体实现方法
        UserAccess userAccess = realMethod.getAnnotation(UserAccess.class);

        if (userAccess != null) {
            //获取注解里的值
            System.err.println("second around:" + userAccess.name());
            System.err.println("second around:" + userAccess.type());
            if (userAccess.type() == EmUserAccess.OPEN) {
                return pjp.proceed();
            }
        }
        String token = getAccessTokenFromRequest(req);

        if (StringUtils.isBlank(token)) {
            log.info(TOKEN_FAIL);
            return ResponseUtil.tokenFail(TOKEN_FAIL);
        }

        HashMap<String, Object> map = UserManage.getUserByToken(token);

        if (map == null) {
            log.info(TOKEN_FAIL);
            return ResponseUtil.tokenFail(TOKEN_FAIL);
        }
        //存入 ThreadLocal
        userManage.setUserToken(token);
        redisTemplate.expire(token, 2, TimeUnit.HOURS);//设置token 有效期为2小时(每次更新token过期时间)
        return pjp.proceed();

    }


    protected String getAccessTokenFromRequest(HttpServletRequest request) {
        String accessToken = request.getHeader(TOKEN);
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = request.getParameter(TOKEN);
        }
        return accessToken;
    }

    /**
     * 获取请求获取IP
     *
     * @param request
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}
